package com.cheyunkeji.er.activity.fast_evaluate;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.adapter.citymodel.City300SortAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.Car300CityInfoList;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.Car300CityListPinyinComparator;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.cityview.SideBar;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;

public class FastEvaluateCitySelectActivity extends BaseActivity implements SideBar.OnTouchingLetterChangedListener, AdapterView.OnItemClickListener,
        ActivityCompat.OnRequestPermissionsResultCallback,
        TencentLocationListener {


    private static final int SET_LOCATE_CITY_NAME = 1;

    private static final int MATCH_AMAP_CITY_WITH_CAR300_CITY_LIST = 2;

    private static final String TAG = FastEvaluateCitySelectActivity.class.getSimpleName();
    private static final int PERMISSON_REQUESTCODE = 0;
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.lv_city_list)
    ListView lvCityList;
    @BindView(R.id.dialog)
    TextView dialog;
    @BindView(R.id.sidebar)
    SideBar sidebar;
    @BindView(R.id.activity_fast_evaluate_city_select)
    LinearLayout activityFastEvaluateCitySelect;
    @BindView(R.id.tv_locate_city)
    TextView tvLocateCity;
    @BindView(R.id.ll_located_city)
    LinearLayout llLocatedCity;

    private TencentLocationManager locationManager;
    private TencentLocationRequest locationRequest;

    //    省份、城市名数组
//    private String[] currentLocateCity = new String[2];
    private ArrayList<Car300CityInfoList.CityListBean> cityList;
    private String locateCity, locateProvince;
    private City300SortAdapter cityListAdapter;
    private Car300CityInfoList.CityListBean currentCity;

    private Boolean hasLocalPosition = false;

    private Handler uiHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case MATCH_AMAP_CITY_WITH_CAR300_CITY_LIST:

                    if (null != cityList && cityList.size() != 0) {

                        matchCityWithCar300CityList((String) msg.obj);
                    }

                    break;

                case SET_LOCATE_CITY_NAME:

                    break;

                default:
                    break;
            }

        }
    };
    private boolean isNeedCheck = true;

    private void matchCityWithCar300CityList(String amapCityName) {
        for (int i = 0; i < cityList.size(); i++) {
            if (amapCityName.contains(cityList.get(i).getCity_name())) {
                currentCity = cityList.get(i);
                llLocatedCity.setEnabled(true);
                break;
            }
        }
    }

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_fast_evaluate_city_select);
        ButterKnife.bind(this);

        loadCarListInfo();
        initLocation();
    }

    @Override
    protected void initView() {
        vTopbar.setLeftBack();
        vTopbar.setTitle("选择城市");
        llLocatedCity.setEnabled(false);

        sidebar.setTextView(dialog);
        sidebar.setTextColor(getResources().getColor(R.color.half_transparent_blue_2));
        llLocatedCity.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    private void initLocation() {
        // 用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
        locationManager = TencentLocationManager.getInstance(this);
        locationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
        // 创建定位请求
        locationRequest = TencentLocationRequest.create();
        // 设置定位周期（位置监听器回调周期）为3s
        locationRequest.setInterval(3000);
    }

    private void loadCarListInfo() {
        HashMap<String, String> params = new HashMap<>();
        ApiClient.postForm(HttpConstants.CAR300_CITY_LIST, params, new RespCallback<Car300CityInfoList>() {
            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onSuccess(Car300CityInfoList data) {
                fillCityList(data);
            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }

        });
    }

    private void fillCityList(Car300CityInfoList data) {
        if (data != null) {
//            currentLocateCity[0] = data.getProv_id();
//            currentLocateCity[1] = data.getCity_id();
            ArrayList<String> firstLetters = new ArrayList<>();
            cityList = (ArrayList<Car300CityInfoList.CityListBean>) data.getCity_list();
            for (int i = 0; i < cityList.size(); i++) {
//              过滤掉小写字母 t、s
                if (!firstLetters.contains(cityList.get(i).getInitial()) && (byte) 'A' <= cityList.get(i).getInitial().getBytes()[0] && cityList.get(i).getInitial().getBytes()[0] <= (byte) 'Z') {
                    firstLetters.add(cityList.get(i).getInitial());
                }
            }

            Log.e(TAG, "fillCityList:  大写字母序列 ： " + firstLetters.toString());

            Collections.sort(firstLetters);
            sidebar.setIndexText(firstLetters);
            Collections.sort(cityList, new Car300CityListPinyinComparator());
            cityListAdapter = new City300SortAdapter(this, cityList);
            lvCityList.setAdapter(cityListAdapter);
            sidebar.setVisibility(View.VISIBLE);
            initEvents();

            if(hasLocalPosition){
                matchCityWithCar300CityList(tvLocateCity.getText().toString());
            }
        }
    }

    private void initEvents() {
        sidebar.setOnTouchingLetterChangedListener(this);
        lvCityList.setOnItemClickListener(this);
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        //该字母首次出现的位置
        int position = cityListAdapter.getPositionForSection(s.charAt(0));
        if (position != -1) {
            lvCityList.setSelection(position);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        takeDataBack(cityList.get(position));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_located_city:
                if (null != currentCity)
                    takeDataBack(currentCity);
                break;
            default:
                break;
        }
    }

    /**
     * 返回城市数据
     *
     * @param currentCity
     */
    private void takeDataBack(Car300CityInfoList.CityListBean currentCity) {
        Intent intent = new Intent();
        intent.putExtra(Constants.SELECTED_CITY_OBJECT, currentCity);
        setResult(Constants.RESULT_CODE_OK, intent);
        finish();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
    }

    private void checkPermissions(String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }


    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    this, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }


    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }


    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }


    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    private void destroyLocation() {
        if (locationManager != null) {
            locationManager.removeUpdates(this);
        }
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        if (TencentLocation.ERROR_OK == i) {
            // 定位成功
            if (tencentLocation != null) {
                String lat = String.valueOf(tencentLocation.getLatitude());
                String lon = String.valueOf(tencentLocation.getLongitude());
                String city = tencentLocation.getCity();
                tvLocateCity.setText(city);

                Message msg = uiHandler.obtainMessage();
                msg.what = MATCH_AMAP_CITY_WITH_CAR300_CITY_LIST;
                msg.obj = city;
                uiHandler.sendMessage(msg);

                hasLocalPosition = true;
            }
        } else {
            // 定位失败
            tvLocateCity.setText("定位失败");
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {}
}
